package com.lxl.xm.common;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import com.arcsoft.face.toolkit.ImageFactory;
import com.arcsoft.face.toolkit.ImageInfo;
import com.lxl.xm.model.dto.student.StudentAddRequest;
import com.lxl.xm.model.entity.Student;
import com.lxl.xm.service.FaceEngineService;
import com.lxl.xm.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;
import java.util.List;

@Slf4j
public class StudentUploadListener implements ReadListener<StudentAddRequest> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    private List<Student> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private StudentService studentService;

    private FaceEngineService faceEngineService;

    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param studentService
     */
    public StudentUploadListener(StudentService studentService, FaceEngineService faceEngineService) {
        this.studentService = studentService;
        this.faceEngineService = faceEngineService;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. It is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(StudentAddRequest data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        Student student = new Student();
        BeanUtils.copyProperties(data,student);
        if (student.getPhoto() != null){
            //图片操作
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<byte[]> responseEntity
                    = restTemplate.getForEntity(student.getPhoto(), byte[].class);
            byte[] imageData = responseEntity.getBody();
            String s = Base64.getEncoder().encodeToString(imageData);
            //解析成人脸特征
            byte[] decode = cn.hutool.core.codec.Base64.decode(s);
            ImageInfo imageInfo = ImageFactory.getRGBData(decode);
            //人脸特征获取
            try {
                byte[] bytes = faceEngineService.extractFaceFeature(imageInfo);
                student.setFaceFeature(bytes);
                student.setFaceId(RandomUtil.randomString(10));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        cachedDataList.add(student);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            // 存储完成清理 list
            saveData();
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        studentService.saveBatch(cachedDataList);
        log.info("存储数据库成功！");
    }

}
